#include "custombutton.h"
#include <QStyle>
#include <QRegularExpression>
#include "models/command.h"
CustomButton::CustomButton(QWidget *parent)
    : YSPushButton(parent)
    , m_isPressed(false)
    , m_group(nullptr)
{
    setFlat(true);
    setFixedSize(70*g_xScale,80*g_xScale);
}

void CustomButton::setGroup(QButtonGroup* group)
{
    m_group = group;
    if (m_group) {
        m_group->addButton(this);
    }
}

QPixmap CustomButton::getBackgroundImage() const
{
    // 从样式表中提取背景图片URL
    QString style = styleSheet();
    QString pattern;

    if (isChecked()) {
        // 如果是选中状态，先尝试获取选中状态的图片
        pattern = "CustomButton:checked\\s*{[^}]*background-image:\\s*url\\((.+?)\\)";
    } else {
        // 否则获取普通状态的图片
        pattern = "CustomButton\\s*{[^}]*background-image:\\s*url\\((.+?)\\)";
    }

    QRegularExpression re(pattern);
    QRegularExpressionMatch match = re.match(style);

    if (match.hasMatch()) {
        QString imageUrl = match.captured(1);
        QPixmap pixmap(imageUrl);
        return pixmap;
    }
    return QPixmap();
}

QColor CustomButton::getTextColor() const
{
    QString style = styleSheet();
    QString pattern;

    if (isChecked()) {
        // 选中状态的文字颜色
        pattern = "CustomButton:checked\\s*{[^}]*color:\\s*([^;\\s]+)";
    } else {
        // 普通状态的文字颜色
        pattern = "CustomButton\\s*{[^}]*color:\\s*([^;\\s]+)";
    }

    QRegularExpression re(pattern);
    QRegularExpressionMatch match = re.match(style);

    if (match.hasMatch()) {
        QString colorStr = match.captured(1);
        return QColor(colorStr);
    }
    return palette().color(QPalette::ButtonText);
}
void CustomButton::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 如果按下状态或选中状态，绘制背景色
    if (m_isPressed || isChecked()) {
        painter.fillRect(rect(), QColor("#00C8FF"));
    }
    else{
         painter.fillRect(rect(), QColor("#00000000"));
    }
    // 获取背景图片
    QPixmap bgImage = getBackgroundImage();

    if(m_nBtnType==TEXT_ICON_UP)
    {
        if (!bgImage.isNull()) {
            // 计算图片的合适大小
            // 图片占按钮高度的60%
            int maxImageHeight = height() * 0.3;
            int maxImageWidth = width() * 0.3;  // 图片最大宽度为按钮宽度的80%

            // 保持宽高比缩放图片
            QSize targetSize = bgImage.size();
            targetSize.scale(maxImageWidth, maxImageHeight, Qt::KeepAspectRatio);

            // 缩放图片
            QPixmap scaledImage = bgImage.scaled(targetSize,
                                                 Qt::KeepAspectRatio,
                                                 Qt::SmoothTransformation);

            QFont buttonFont ;
            buttonFont.setFamily("微软雅黑");
            buttonFont.setPixelSize(int(18*g_xScale));

            // 设置字体
            painter.setFont(buttonFont);
            QFontMetrics fm(buttonFont);
            int textHeight = fm.height();
            int textWidth = fm.horizontalAdvance(text());

            // 计算总高度（图片 + 间距 + 文字）
            int totalHeight = scaledImage.height() + 10 + textHeight;

            // 计算起始Y坐标，使整体垂直居中
            int startY = (height() - totalHeight) / 2;

            // 绘制图片
            int imageX = (width() - scaledImage.width()) / 2;
            painter.drawPixmap(imageX, startY, scaledImage);

            // 绘制文字
            if (!text().isEmpty()) {
                int textX = (width() - textWidth) / 2;
                int textY = startY + scaledImage.height() + 10;

                // 从样式表获取文字颜色
                painter.setPen(getTextColor());
                painter.drawText(textX, textY + fm.ascent(), text());
            }
        }
    }
    else if(m_nBtnType==ICON_CENTER){
        if (!bgImage.isNull()) {
            // 计算图片的合适大小
            // 图片占按钮高度的60%
            int maxImageHeight = height() * 0.6;
            int maxImageWidth = width() * 0.6;  // 图片最大宽度为按钮宽度的80%

            // 保持宽高比缩放图片
            QSize targetSize = bgImage.size();
            targetSize.scale(maxImageWidth, maxImageHeight, Qt::KeepAspectRatio);

            // 缩放图片
            QPixmap scaledImage = bgImage.scaled(targetSize,
                                                 Qt::KeepAspectRatio,
                                                 Qt::SmoothTransformation);

            // 绘制图片
            int imageX = (width() - scaledImage.width()) / 2;
            // 计算起始Y坐标，使整体垂直居中
            int imageY = (height() - scaledImage.height()) / 2;
            painter.drawPixmap(imageX, imageY, scaledImage);
        }
    }
}

void CustomButton::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton) {
        m_isPressed = true;
        update();
    }
    QPushButton::mousePressEvent(event);
}

void CustomButton::mouseReleaseEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton) {
        m_isPressed = false;
        update();
    }
    QPushButton::mouseReleaseEvent(event);
}

void CustomButton::setBtnType(int nType)
{
    m_nBtnType=nType;
}

int CustomButton::btnType()
{
    return m_nBtnType;
}
